package com.example.myapplication;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;
import java.util.Random;

public class PhoneListenService extends Service {

    private final String OUTGOING_CALL = "android.intent.action.NEW_OUTGOING_CALL";
    private final String TAG = "提示";
    private TelephonyManager telephonyManager;
    private PhoneMyListen listen;
    private PhoneMyListenReceiver phoneMyListenReceiver;
    private String callNum;
    private MediaRecorder mediaRecorder;
    private String phoneNumber;
    NotificationCompat.Builder builder;
    String title = "服务";
    String text = "通话监听中";
    private int notificationId;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        listen = new PhoneMyListen();
        telephonyManager.listen(listen, PhoneStateListener.LISTEN_CALL_STATE);
        getOutGongCall();
        start();
        super.onCreate();
    }

    private void getOutGongCall() {

        phoneMyListenReceiver = new PhoneMyListenReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(OUTGOING_CALL);
        registerReceiver(phoneMyListenReceiver, intentFilter);
    }

    class PhoneMyListen extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String iPhoneNumber) {
            super.onCallStateChanged(state, iPhoneNumber);
            phoneNumber = iPhoneNumber;
            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                   try {
                       if (mediaRecorder != null) {
                           mediaRecorder.stop();
                           mediaRecorder.reset();
                           mediaRecorder.release();
                           mediaRecorder = null;
                           Toast.makeText(PhoneListenService.this, "录音保存成功", Toast.LENGTH_SHORT).show();
                           /**
                            * 开启录音上传
                            * thead
                            */
                       }
                   }catch (Exception e){
                       e.printStackTrace();
                       Toast.makeText(PhoneListenService.this, "录音保存失败", Toast.LENGTH_SHORT).show();
                   }
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    phoneNumber = iPhoneNumber;
                    Toast.makeText(PhoneListenService.this, "拨号中", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "拨号中");
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    try {
                    mediaRecorder = new MediaRecorder();
                    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);

                    File autoFile = new File(Environment.getExternalStorageDirectory() + "/Music/");
                    if (!autoFile.exists()) {
                        autoFile.mkdirs();
                    }

                    String saveAmr = Environment.getExternalStorageDirectory() + "/Music/" + DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".3gp";

                    mediaRecorder.setOutputFile(saveAmr);
                    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
                            mediaRecorder.setAudioSamplingRate(11025);
                        }
                        Log.i("状态",String.valueOf(mediaRecorder));
                        mediaRecorder.prepare();
                        mediaRecorder.start();
                        Toast.makeText(PhoneListenService.this, "开始录音", Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "通话中");
                    } catch (Exception e) {
                        e.printStackTrace();
                        mediaRecorder=null;
                        Toast.makeText(PhoneListenService.this, "录音失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    }


    public class PhoneMyListenReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String outgoingNumber = getResultData();
            callNum = outgoingNumber;
            phoneNumber = callNum;
            Log.i(TAG, outgoingNumber);
        }
    }

    public void onDestroy() {
        // 取消电话的监听,采取线程守护的方法，当一个服务关闭后，开启另外一个服务，除非你很快把两个服务同时关闭才能完成
        Intent i = new Intent(this, TelProtectService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(i);
        } else {
            startService(i);
        }
        listen = null;
        unregisterReceiver(phoneMyListenReceiver);
        stop();
        Toast.makeText(this, "关闭了服务", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    private void start() {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationId = new Random().nextInt();
        String channelId = String.valueOf(new Random().nextInt()); //自己生成的用于通知栏的channelId，高版本必备
        NotificationChannel mChannel = new NotificationChannel(channelId, "name", NotificationManager.IMPORTANCE_HIGH);
        mChannel.enableVibration(false);
        mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        manager.createNotificationChannel(mChannel);
        builder = new NotificationCompat.Builder(this, channelId);
        builder.setContentTitle(title)
                .setWhen(System.currentTimeMillis()) //设置通知时间戳
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText(text)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)  //设置将从系统默认值继承哪些通知属性 基本就是用来设置是否通知音效或者震动
                .setAutoCancel(true)
//                .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT))   //点击通知后的跳转
//                .setTicker(text) //收到通知后从顶部弹出精简版通知
                .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); //自定义震动的频率
        Notification notification;
        notification = builder.build();
        notification.flags |= Notification.FLAG_NO_CLEAR;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { // 注意notification也要适配Android 8 哦
            startForeground(notificationId,notification);// 通知栏标识符 前台进程对象唯一ID
        }else{
            manager.notify(notificationId, notification);
        }
        Toast.makeText(this, "开启Service服务", Toast.LENGTH_SHORT).show();
    }

    private void stop() {
        if (notificationId != 0) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            notificationManager.cancel(notificationId);
        }
    }
}
